package com.ebt.m.customer.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import com.ebt.m.AppInitService;
import com.ebt.m.R;
import com.ebt.m.commons.utils.RxUtil;
import com.ebt.m.commons.widgets.BaseRxDialogFragment;
import com.ebt.m.customer.constant.CustomerConstant;
import com.ebt.m.customer.event.EventCustomerChooseSearch;
import com.ebt.m.customer.model.CustomerModelNew;
import com.ebt.m.customer.net.json.CustomerDetailJson;
import com.ebt.m.customer.util.CustomerConvertUtil;
import com.ebt.m.customer.util.ToastUtil;
import com.ebt.m.data.entity.Customer;
import com.ebt.m.data.rxModel.api.EBTAPI;
import com.ebt.m.view.ClearEditText;
import com.jakewharton.rxbinding2.view.RxView;

import org.greenrobot.eventbus.EventBus;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 选择客户页面
 */
public class DialogCustomerChoose extends BaseRxDialogFragment {

    public interface CustomerChooseListener {
        void onPick(Customer customer);

        void onCancel();
    }

    public static final String BUNDLE_FLAG_TITLE = "title";
    public static final String BUNDLE_FLAG_CHOOSE_MODE = "mode";
    public static final String CUSTOMER_CHOOSE_MODE_SINGLE = "single";

    private Bundle mGetBundle;
    private String mMode = CUSTOMER_CHOOSE_MODE_SINGLE;

    private FragmentCustomerChoose mFragmentCustomerChoose;
    private FragmentCustomerChoose.CustomerChooseListener mContentCustomerChooseListener;

    private static final String TAG_FRAGMENT_CHOOSE = "TAG_FRAGMENT_CHOOSE";

    private CustomerChooseListener mDialogCustomerChooseListener;

    public void setCustomerChooseListener(CustomerChooseListener customerChooseListener) {
        mDialogCustomerChooseListener = customerChooseListener;
    }

    private ClearEditText mClearEditText;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.choose_dialog);
        mGetBundle = getArguments();
        if (mGetBundle != null) {
            mMode = mGetBundle.getString(BUNDLE_FLAG_CHOOSE_MODE);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.dialog_customer_choose, container);
    }

    @Override
    public void onActivityCreated(Bundle arg0) {
        super.onActivityCreated(arg0);
        initValues();
        initViews();
    }

    public static DialogCustomerChoose newInstance(String title, DialogCustomerChoose.CustomerChooseListener listener) {
        Bundle bundle = new Bundle();
        bundle.putString(BUNDLE_FLAG_TITLE, title);

        DialogCustomerChoose dialogCustomerChoose = new DialogCustomerChoose();
        dialogCustomerChoose.setCustomerChooseListener(listener);
        dialogCustomerChoose.setArguments(bundle);

        return dialogCustomerChoose;
    }

    public void initValues() {
        mContentCustomerChooseListener = new FragmentCustomerChoose.CustomerChooseListener() {
            @Override
            public void onPick(CustomerModelNew customer) {
                getDetailInfoOnPick(customer);
            }

            @Override
            public void onCancel() {
                if (mDialogCustomerChooseListener != null) {
                    mDialogCustomerChooseListener.onCancel();
                }
                dismiss();
            }
        };
    }

    private void getDetailInfoOnPick(CustomerModelNew customer) {
        if (customer != null) {
            String customerId = customer.getCustomerUuid();
            EBTAPI ebtapi = AppInitService.getEbtApi();
            ebtapi.getCustomerDetail(customerId).compose(RxUtil.rxSchedulerHelper()).subscribe(getCustomerDetailSubscriber());
        }
    }

    private Observer<CustomerDetailJson> getCustomerDetailSubscriber() {
        return new Observer<CustomerDetailJson>() {

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onComplete() {
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ToastUtil.showToast(getContext().getResources().getString(R.string.network_fail));
            }

            @Override
            public void onNext(CustomerDetailJson customerDetailJson) {

                if (customerDetailJson == null) {
                    ToastUtil.showToast("客户不存在");
                    return;
                }
                if (customerDetailJson.error != null) {
                    ToastUtil.showToast(getContext().getResources().getString(R.string.network_fail));
                    return;
                }
                if (customerDetailJson.error == null) {
                    if (customerDetailJson.data == null) {
                        ToastUtil.showToast(getContext().getResources().getString(R.string.network_fail));
                        return;
                    } else {
                        if (mDialogCustomerChooseListener != null) {
                            mDialogCustomerChooseListener.onPick(
                                    CustomerConvertUtil.convertCustomerDetailToCustomer(customerDetailJson.data));
                        }
                        dismiss();
                    }
                }
            }
        };
    }

    public void initViews() {
        setDefaultFragment(mMode, R.id.content, mContentCustomerChooseListener);
        mClearEditText = (ClearEditText) getView().findViewById(R.id.et_search);
        mClearEditText.setTextWatcherCallback(new ClearEditText.TextWatcherCallback() {
            @Override
            public void onAfterTextChanged(EditText editText, Editable editable) {
                search(editText.getText().toString().trim());
            }
        });
        RxView.clicks(getView().findViewById(R.id.v_back))
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    pressCancelButton();
                });
        RxView.clicks(getView().findViewById(R.id.v_add))
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    pressAddButton();
                });
    }

    private void search(String keywords) {
        EventBus.getDefault().post(new EventCustomerChooseSearch(keywords));
    }


    private void setDefaultFragment(String mode, int viewId, FragmentCustomerChoose.CustomerChooseListener customerChooseListener) {
        FragmentManager fm = getChildFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        mFragmentCustomerChoose = new FragmentCustomerChoose();
        mFragmentCustomerChoose.setChooseListener(customerChooseListener);
        transaction.replace(viewId, mFragmentCustomerChoose, TAG_FRAGMENT_CHOOSE);
        transaction.commit();
    }

    private void pressAddButton() {
        Intent intent = new Intent(getContext(), ActivityCustomerDetail.class);
        intent.putExtra(CustomerConstant.CUSTOMER_DETAIL_MODE, CustomerConstant.CUSTOMER_DETAIL_MODE_ADD);
        intent.putExtra(CustomerConstant.CustomerDetail.CHOOSE, true);
        getContext().startActivity(intent);
        ((Activity) getContext()).overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
    }

    private void pressCancelButton() {
        if (mDialogCustomerChooseListener != null) {
            mDialogCustomerChooseListener.onCancel();
        }
        dismiss();
    }

}